package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mapper.RequestMapper;
import com.demo.pojo.entity.Request;
import com.demo.service.RequestService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 诉求服务实现
 */
@Service
public class RequestServiceImpl extends ServiceImpl<RequestMapper, Request> implements RequestService {
    
    @Override
    public boolean submitRequest(Request request) {
        try {
            System.out.println("📝 提交诉求: " + request.getTitle());
            
            // 设置默认值
            if (request.getStatus() == null) {
                request.setStatus("PENDING");
            }
            if (request.getPriority() == null) {
                request.setPriority("NORMAL");
            }
            if (request.getSubmitTime() == null) {
                request.setSubmitTime(LocalDateTime.now());
            }
            
            boolean result = save(request);
            System.out.println("✅ 诉求提交" + (result ? "成功" : "失败"));
            return result;
            
        } catch (Exception e) {
            System.err.println("❌ 提交诉求失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public List<Request> getUserRequests(Long userId, String userType, String status) {
        try {
            System.out.println("🔍 查询用户诉求: userId=" + userId + ", userType=" + userType + ", status=" + status);
            
            QueryWrapper<Request> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId)
                   .eq("user_type", userType);
            
            if (status != null && !status.isEmpty() && !status.equals("ALL")) {
                wrapper.eq("status", status);
            }
            
            wrapper.orderByDesc("submit_time");
            
            List<Request> list = list(wrapper);
            System.out.println("✅ 查询到 " + list.size() + " 条诉求记录");
            return list;
            
        } catch (Exception e) {
            System.err.println("❌ 查询用户诉求失败: " + e.getMessage());
            e.printStackTrace();
            return List.of();
        }
    }
    
    @Override
    public List<Request> getAllRequests(String status, String userType, String requestType) {
        try {
            System.out.println("🔍 管理员查询所有诉求: status=" + status + ", userType=" + userType + ", requestType=" + requestType);
            
            QueryWrapper<Request> wrapper = new QueryWrapper<>();
            
            if (status != null && !status.isEmpty() && !status.equals("ALL")) {
                wrapper.eq("status", status);
            }
            if (userType != null && !userType.isEmpty() && !userType.equals("ALL")) {
                wrapper.eq("user_type", userType);
            }
            if (requestType != null && !requestType.isEmpty() && !requestType.equals("ALL")) {
                wrapper.eq("request_type", requestType);
            }
            
            wrapper.orderByDesc("submit_time");
            
            List<Request> list = list(wrapper);
            System.out.println("✅ 查询到 " + list.size() + " 条诉求记录");
            return list;
            
        } catch (Exception e) {
            System.err.println("❌ 查询所有诉求失败: " + e.getMessage());
            e.printStackTrace();
            return List.of();
        }
    }
    
    @Override
    public boolean processRequest(Long requestId, Long adminId, String adminName, String status, String adminReply) {
        try {
            System.out.println("⚙️ 处理诉求: requestId=" + requestId + ", status=" + status);
            
            Request request = getById(requestId);
            if (request == null) {
                System.err.println("❌ 诉求不存在");
                return false;
            }
            
            request.setAdminId(adminId);
            request.setAdminName(adminName);
            request.setStatus(status);
            request.setAdminReply(adminReply);
            
            if ("PROCESSING".equals(status) && request.getProcessTime() == null) {
                request.setProcessTime(LocalDateTime.now());
            }
            
            if ("RESOLVED".equals(status) || "REJECTED".equals(status)) {
                request.setResolveTime(LocalDateTime.now());
            }
            
            boolean result = updateById(request);
            System.out.println("✅ 诉求处理" + (result ? "成功" : "失败"));
            return result;
            
        } catch (Exception e) {
            System.err.println("❌ 处理诉求失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean deleteRequest(Long requestId) {
        try {
            System.out.println("🗑️ 删除诉求: requestId=" + requestId);
            boolean result = removeById(requestId);
            System.out.println("✅ 诉求删除" + (result ? "成功" : "失败"));
            return result;
        } catch (Exception e) {
            System.err.println("❌ 删除诉求失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getRequestStats() {
        try {
            System.out.println("📊 获取诉求统计");
            
            Map<String, Object> stats = new HashMap<>();
            
            // 总数
            long total = count();
            stats.put("total", total);
            
            // 待处理
            QueryWrapper<Request> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("status", "PENDING");
            long pending = count(pendingWrapper);
            stats.put("pending", pending);
            
            // 处理中
            QueryWrapper<Request> processingWrapper = new QueryWrapper<>();
            processingWrapper.eq("status", "PROCESSING");
            long processing = count(processingWrapper);
            stats.put("processing", processing);
            
            // 已解决
            QueryWrapper<Request> resolvedWrapper = new QueryWrapper<>();
            resolvedWrapper.eq("status", "RESOLVED");
            long resolved = count(resolvedWrapper);
            stats.put("resolved", resolved);
            
            // 已拒绝
            QueryWrapper<Request> rejectedWrapper = new QueryWrapper<>();
            rejectedWrapper.eq("status", "REJECTED");
            long rejected = count(rejectedWrapper);
            stats.put("rejected", rejected);
            
            // 学生诉求数
            QueryWrapper<Request> studentWrapper = new QueryWrapper<>();
            studentWrapper.eq("user_type", "STUDENT");
            long studentCount = count(studentWrapper);
            stats.put("studentCount", studentCount);
            
            // 教师诉求数
            QueryWrapper<Request> teacherWrapper = new QueryWrapper<>();
            teacherWrapper.eq("user_type", "TEACHER");
            long teacherCount = count(teacherWrapper);
            stats.put("teacherCount", teacherCount);
            
            System.out.println("✅ 统计完成: " + stats);
            return stats;
            
        } catch (Exception e) {
            System.err.println("❌ 获取诉求统计失败: " + e.getMessage());
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}

